import React, { useState } from 'react'
import { View, Picker } from '@tarojs/components'
import Taro, {useDidShow } from '@tarojs/taro'
import { AtInput, AtButton, AtMessage, AtList, AtListItem }  from 'taro-ui'
import { request } from '@/utils'
import './index.less'

const BookingEdit = () => {
  const [userId, setUserId] = useState('')
  const [selectedName, setSelectedName] = useState('请选择车队')
  const [selector, setSelector] = useState([])
  const [oilMass, setOilMass] = useState('')
  const [amount, setAmount] = useState('')
  const handleChange = (e, type) => {
    if(type === 2) {
      setOilMass(e)
    }
    if(type === 3) {
      setAmount(e)
    }
  }
  const onFillChange = (e) => {
    const { detail: { value }} = e
    setUserId(selector[value].userId)
    setSelectedName(selector[value].name)
  }

  const getCarList = async () => {
    const { list } = await request({url: 'hkshihua/user/motorcade/getMotorcadeList', data: {pageSize: 100000}})
    const newList = []
    list.forEach(item => {
      if(item.role !== 'ADMINISTRATOR') {
        newList.push(item)
      }
    });
    setSelector(newList)
  }

  useDidShow(() => {
    getCarList()
  })

  const handleSave =async () => {
    if(!userId) {
      Taro.atMessage({ message: '请输入车队', type: 'error' })
      return
    }
    if(!oilMass) {
      Taro.atMessage({ message: '请输入油量', type: 'error' })
      return
    }
    if(!amount) {
      Taro.atMessage({ message: '请输入金额', type: 'error' })
      return
    }
    Taro.showLoading({mask: true})
    const {error} = await request({ url: 'hkshihua/user/motorcadeOilMass',header: {"Content-Type": "application/json"},method: 'post', data: JSON.stringify({userId, amount, oilMass})})
    if(error) return
    Taro.atMessage({ message: '保存成功', type: 'success'})
    Taro.navigateBack()
  }
  return (
    <View>
      <AtMessage />
       <View className='edit'>
       <Picker mode='selector' range={selector} rangeKey='name' onChange={onFillChange} style={{paddingLeft: 0}}>
          <AtList>
            <AtListItem
              title='车队'
              extraText={selectedName}
            />
          </AtList>
        </Picker>
        <AtInput cursor={-1} title='油量' name='oilMass' type='number' placeholder='请输入油量' value={oilMass} onChange={(e) => handleChange(e, 2)} />
        <AtInput cursor={-1} title='金额' name='amount' type='number' placeholder='请输入金额' value={amount} onChange={(e) => handleChange(e, 3)} />
      </View>
     <View className='btn'>
      <AtButton type='primary' full onClick={handleSave}>保存</AtButton>
     </View>
    </View>
  )
}

export default BookingEdit
